const router = require("express").Router();
const AdminModel = require("../../model/schema/adminModel");
const { md5, judgeForm } = require("../../tools/tools");

router.get("/", (req, res) => {
    res.render("admin/register/register.html", {
        tipMessage: "",
        oldData: {},
    });
});

router.post("/doRegister", async(req, res) => {
    let flag = true;
    // 如果数据为null，则直接为false
    if (!req.body.username ||
        !req.body.password ||
        !req.body.ensureP ||
        !req.body.mobile ||
        !req.body.invitationCode
    ) {
        flag = false;
    }

    let formData = req.body;
    try {
        if (flag) {
            // 对数据检测合格性
            let judgeResultObj = judgeForm(formData);
            if (judgeResultObj.flag) {
                // 验证合格

                // 判断邀请码是否和数据库那边的一样
                if (formData.invitationCode !== "123") {
                    res.render("admin/register/register.html", {
                        tipMessage: "邀请码错误",
                        oldData: formData,
                    });
                }

                formData.password = md5(formData.password); // password加密

                let newAdmin = new AdminModel(formData);

                await newAdmin.save();

                req.session.curRegisterUM = formData.username; // 刚注册完的用户名
                res.redirect(`/${req.app.locals.adminPath}/login`);
            } else {
                // 验证不合格，返回注册页
                res.render("admin/register/register.html", {
                    tipMessage: judgeResultObj.message,
                    oldData: formData,
                });
            }
        } else {
            res.render("admin/register/register.html", {
                tipMessage: "数据填写错误",
                oldData: {},
            });
        }
    } catch (error) {
        // 由于用户名是uniquer 因此如果用户名相同且提交就会抛出错误
        // 因为之前把formData.password进行md5加密了，所以这里恢复一下
        formData.password = formData.ensureP;
        res.render("admin/register/register.html", {
            tipMessage: "用户名已存在",
            oldData: req.body,
        });
    }
});

module.exports = router;